﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Orgs;
using SmartSpace.Web;

namespace SmartSpace.WebApp.Modules.Orgs.Pages
{
    public partial class Node_Add : SsTemplatePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.txt_parentName.Enabled = false;
            string nodeId = Request.QueryString["nodeId"] ?? String.Empty;
            OrgsService services = new OrgsService();
            if (!IsPostBack)
            {
                if (nodeId != "")
                {
                    Node node = services.GetNode(new Guid(nodeId), true);
                    this.txt_parentName.Text = node.Name.ToString();
                    BindSelectForNode(node.TypeId);
                }
                else {
                    BindSelectForRoot(services.GetTypes().Data);
                }
            }
        }

        public void BindSelectForRoot(List<NodeType> list)
        {
            ddl_nodeType.DataSource = list;
            ddl_nodeType.DataTextField = "Caption";
            ddl_nodeType.DataValueField = "Id";
            ddl_nodeType.DataBind();
        }

        public void BindSelectForNode(Guid typeid)
        {
            OrgsService services = new OrgsService();
            ListResult<NodeType> list = services.GetSubTypes(typeid);

            ddl_nodeType.DataSource = list.Data;
            ddl_nodeType.DataTextField = "Caption";
            ddl_nodeType.DataValueField = "Id";
            ddl_nodeType.DataBind();
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            String nodeId = Request.QueryString["nodeId"] ?? String.Empty;
            Node node = new Node();
            if (nodeId == "")
            {
                node.ParentId = null;
            }
            else
            {
                node.ParentId = new Guid(nodeId);
            }
            node.Id = Guid.NewGuid();
            node.Code = this.org_tree_code.Text;
            node.Name = this.org_tree_name.Text;
            node.TypeId = new Guid(this.ddl_nodeType.SelectedItem.Value);
            node.ShortName = this.txt_ShortName.Text;
            node.Description = this.txt_Description.Value;
            
            OrgsService services = new OrgsService();

            bool bl = services.SaveNode(node);
            if (bl)
            {
                Response.Redirect("OrgTree.aspx?nodeId=" + nodeId);
            }
        }
    }
}